import { useEffect, useContext, useState, useCallback } from "react";
import { View, Text, Alert, ScrollView, Pressable, Linking } from "react-native";
import { useSelector, useDispatch } from "react-redux";
import { setCurPlayData } from "@/store/slices/index";
import type { RootState } from "@/store";

import DocumentPicker from "react-native-document-picker";

import fso from "@/utils/FileOperate/operate";
import sm from "@/utils/ScheduleManage/operate";

import Btn from "@/components/Btn";
import SchduleInfoCard, { getPlayMaterialComp } from "@/components/SchduleInfoCard";
import ModalBox from "@/components/ModalBox";

import globalMethods from "@/GlobalMethodProvider";
import { getTypeabel } from "@/config/dictMap";
import { WidgetProviderContext } from "@/WidgetProvider";

import { scheduleSqlh, materialSqlh } from "@/sqlite/exports";
import type { ScheduleSqliteType, MaterialSqliteType } from "@/sqlite/exports";

import config from "@/config";
import commonStyles from "@/styles";
import theme from "@/styles/theme";

import styles from "./styles";

/** 页面状态类型 */
type StateType = {
  /** 本地所有的素材数据 */
  allMaterial: MaterialSqliteType[];
  /** 当前素材管理的排期 */
  curSchedule: ScheduleSqliteType | null;
  /** 当前选择的素材 */
  selectMaterial: MaterialSqliteType | null;
  /** 查看素材文件显示弹框 */
  visible: boolean;
};

/** 素材信息 */
const MaterialInfo = () => {
  const [state, _setState] = useState<StateType>({
    allMaterial: [],
    curSchedule: null,
    selectMaterial: null,
    visible: false
  });

  // 通用更新状态单个
  const setState = useCallback((field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  }, []);

  // 通用更新状态(对象)
  const setObjState = useCallback((obj: Partial<typeof state>) => {
    _setState(_state => {
      return { ..._state, ...obj };
    });
  }, []);

  const context = useContext(WidgetProviderContext);

  const dispatch = useDispatch();

  const storeRedux = useSelector((state: RootState) => state);

  // 当前播放的素材信息
  const curMaterial = storeRedux.index.curPlayData.rawData;
  console.log("当前播放的素材信息: ", curMaterial);

  /** 获取初始化参数 */
  const getInitData = useCallback(async () => {
    try {
      if (materialSqlh) {
        const list = await materialSqlh.getList<MaterialSqliteType[]>();
        setState("allMaterial", list);
      } else {
        globalMethods.$error("素材数据库初始化失败");
      }
    } catch (err) {
      console.log("err: ", err);
    }
  }, [setState]);

  /** 打开文件 */
  const openFile = (material: MaterialSqliteType) => {
    // Alert.alert("提示", "确定要打开文件吗?", [
    //   { text: "取消", style: "cancel" },
    //   {
    //     text: "确定",
    //     onPress: () => {
    //       Module.actionViewIntent(material.downFileToNativePath, "mp4");
    //     }
    //   }
    // ]);

    if (material.isDown === "2") {
      setObjState({ visible: true, selectMaterial: material });
    } else {
      globalMethods.$showMessage({
        type: "toast",
        position: "top",
        message: "该素材还未下载"
      });
    }
  };

  /** 打开下载地址 */
  const openDownFileurl = (url: string) => {
    Alert.alert("提示", "确定要下载该文件吗?", [
      { text: "取消", style: "cancel" },
      {
        text: "确定",
        onPress: () => {
          Linking.openURL(url);
        }
      }
    ]);
  };

  /** 查看排期数据 */
  const viewScheduleInfo = async (material: MaterialSqliteType) => {
    console.log("material: ", material);
    try {
      if (scheduleSqlh) {
        const res = await scheduleSqlh.getByCustom<ScheduleSqliteType>({
          code: material.parentCode
        });
        if (res.length === 0) {
          globalMethods.$warning(`【${material.name}】没有查询到关联的的排期数据`);
          return;
        } else if (res.length > 1) {
          globalMethods.$warning(`【${material.name}】查询到多个关联的的排期数据`);
          return;
        }
        const curSchedule = res[0];
        setState("curSchedule", curSchedule);

        globalMethods.$showModalBox({
          title: curSchedule.name,
          hideCloseBtn: true,
          dismissable: false,
          contentComponent() {
            return (
              <ScrollView style={{ minHeight: 200, width: "100%" }}>
                <SchduleInfoCard schedule={curSchedule} />
              </ScrollView>
            );
          }
        });
      } else {
        globalMethods.$error("排期数据库初始化失败");
      }
    } catch (err) {
      console.log("err: ", err);
      globalMethods.$error("发生了错误: " + err);
    }
  };

  useEffect(() => {
    getInitData();
  }, [getInitData]);

  const DevComp = config.IS_DEBUG && (
    <ScrollView horizontal>
      <View style={{ flex: 1, flexDirection: "row", gap: 10 }}>
        <Btn
          text="关闭调试页面"
          type="primary"
          onClick={() => {
            context?.closeDrawer();
          }}
        />
        <Btn
          text="已下载的素材"
          type="primary"
          onClick={() => {
            sm.getDownloadedMaterial()
              .then(res => {
                console.log("res: ", res);
              })
              .catch(err => {
                console.log("err: ", err);
              });
          }}
        />
      </View>
    </ScrollView>
  );

  const EmptyComp = <Text>本地暂无素材信息</Text>;

  const AllMaterialComp = state.allMaterial.map((material, i) => {
    return (
      <View style={styles.item} key={i}>
        {curMaterial?.sourceId === material.sourceId && <Text style={styles.curTip}>当前播放</Text>}

        <View style={styles.label}>
          <View style={styles.indexContainer}>
            <Text style={styles.index}>{i + 1}</Text>
          </View>
          <Text style={styles.text}>{material.startTime}</Text>
          <Text style={styles.text}>至</Text>
          <Text style={styles.text}>{material.endTime}</Text>
          <Btn
            text="关联排期"
            type="primary"
            btnTextStyle={{ fontSize: 9 }}
            containerStyle={{ height: 24 }}
            onClick={() => viewScheduleInfo(material)}
          />
        </View>

        <View style={[commonStyles.border, styles.info]}>
          <Text style={styles.text}>素材目录: {fso.formatPath(fso.resourceDir)}</Text>
          <Text style={styles.text}>素材名称: {material.name}</Text>
          <Text style={styles.text}>素材编号: {material.code}</Text>
          <Text style={styles.text}>素材大小: {(Number(material.size) / 1024 / 1024).toFixed(2)}MB</Text>
          <Text style={styles.text}>素材时长: {material.duration}</Text>
          <Text style={styles.text}>素材下发机构: {material.officeName}</Text>
          <Text style={styles.text}>
            素材播放分辨率: {material.resolution}
            {material.resolution === "0*0" && "（自适应）"}
          </Text>
          <Text style={styles.text}>素材入库时间: {material.putLibTime}</Text>
          <Text style={styles.text}>素材类型: {getTypeabel(material.type)}</Text>
          <Text style={styles.text}>
            是否下载:
            <Text
              style={{
                color: material.isDown === "1" ? theme.danger : theme.primary,
                fontWeight: "bold"
              }}
            >
              {material.isDown === "2" ? "是" : "否"}
            </Text>
          </Text>
          <Text style={styles.text}>
            素材本地地址:
            <Text style={styles.link} onPress={() => openFile(material)}>
              {material.downFileToNativePath}
            </Text>
          </Text>
          <Text style={styles.text}>
            素材下载地址:
            <Text onPress={() => openDownFileurl(material.downFileUrl)}>{material.downFileUrl}</Text>
          </Text>
        </View>
      </View>
    );
  });

  const MaterialComp = (
    <ScrollView style={styles.container}>
      <Pressable>
        {DevComp}

        {state.allMaterial.length > 0 ? AllMaterialComp : EmptyComp}
      </Pressable>

      <ModalBox
        visible={state.visible}
        dismissable={false}
        title={state.selectMaterial?.name}
        hideConfirmBtn
        onClose={() => setState("visible", false)}
        closeBtnText="关闭"
      >
        <ScrollView style={{ maxHeight: 300, width: "100%" }}>
          <View style={{ height: 300 }}>{state.selectMaterial && getPlayMaterialComp(state.selectMaterial)}</View>
        </ScrollView>
      </ModalBox>
    </ScrollView>
  );

  return MaterialComp;
};

export default MaterialInfo;
